package com.dragee.modules.work.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragee.common.PageUtils;
import com.dragee.config.exception.BusinessException;
import com.dragee.constants.CommonConstants;
import com.dragee.modules.work.dao.ShopGoodsDao;
import com.dragee.modules.work.entity.ShopGoodsEntity;
import com.dragee.modules.work.service.ShopGoodsService;
import com.dragee.utils.WrapperUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

@Service("shopGoodsService")
public class ShopGoodsServiceImpl extends ServiceImpl<ShopGoodsDao, ShopGoodsEntity> implements ShopGoodsService {


    @Resource
    private ShopGoodsDao shopGoodsDao;

    private String business = "shopGoods";
    /**
    * 列表
    */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        int limit = params.get(CommonConstants.LIMIT) == null
                ?CommonConstants.LIMIT_SIZE:Integer.parseInt(params.get(CommonConstants.LIMIT).toString());
        int start = params.get(CommonConstants.START) == null
                ?CommonConstants.START_SIZE:Integer.parseInt(params.get(CommonConstants.START).toString());
        QueryWrapper<ShopGoodsEntity> wrapper =
                WrapperUtil.getWrapper(business, params, ShopGoodsEntity.class);
        IPage<ShopGoodsEntity> page = new Page<>(start, limit);
        page = baseMapper.selectPage(page, wrapper.select());
        return new PageUtils(page);
    }

    @Override
    public void addKunCun(String shopId, String goodId, Integer sum) {
        optionKunCun(shopId, goodId, sum, 1);
    }

    @Override
    public void removeKunCun(String shopId, String goodId, Integer sum) {
        optionKunCun(shopId, goodId, sum, 0);
    }

    private void optionKunCun (String shopId, String goodId, Integer sum, int type) {
        ShopGoodsEntity good = getOne(new QueryWrapper<ShopGoodsEntity>()
                .eq("shopId", shopId)
                .eq("id", goodId), false);
        if (good == null) {
            return;
        }
        int result = 0;
        if (type == 1) {
            // 入库
            result = good.getSum() + sum;
        } else if (type == 0) {
            // 出库
            result = good.getSum() - sum;
        }
        if (result < 0) {
            throw new BusinessException(good.getName() + "库存不足, 无法操作");
        }
        good.setSum(result);
        saveOrUpdate(good);
    }
}